<?php

/**
* alltosun.com log公用函数 log_helper.php
* ============================================================================
* 版权所有 (C) 2009-2012 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 钱有明 (qianym@alltosun.com) $
* $Date: 2012-11-26 下午7:16:56 $
* $Id: log_helper.php 29003 2014-06-03 11:19:34Z qianym $
*/

class log_helper
{
    /**
     * 拼装log信息
     * @param int $log_id
     * @return array
     */
    public static function generate_log_info($log_id)
    {
        $curr_user_id = user_helper::get_user_id();
        $log_intro = $notification_intro = $mail_intro ='';
        $return_info = array('log_intro'=>$log_intro, 'notification_intro'=>$notification_intro, 'mail_intro'=>$mail_intro);

        $log_info = get_res_info('log', $log_id);
        if (empty($log_info)) {
            return $return_info;
        }
        $res_info = get_res_info($log_info['res_name'], $log_info['res_id']);

        // 操作人：
        $op_name_str  = user_helper::display_name($log_info['op_id']);

        $real_res_info = $res_info;
        if ('comment' == $log_info['res_name']) {
            $real_res_info = get_res_info($res_info['res_name'], $res_info['res_id']);
            if (empty($real_res_info)) {
                return $return_info;
            }
        } else {
            // 资源类型：任务，文件
            if ($log_info['res_name'] == 'group') {
                $group_info = get_res_info('group', $log_info['res_id']);
                if ($group_info && $group_info['type'] == 1) {
                    $res_name_ch = '部门';
                } else {
                    $res_name_ch = '项目';
                }
            } else if ($log_info['res_name'] == 'file' && $res_info['file_type'] == 1) {
                $res_name_ch = '目录';
            } else {
                $res_name_ch  = log_config::$log_res_relation[$log_info['res_name']];
            }
            // 资源的title
            if ($log_info['res_name'] == 'file' && $res_info['file_type'] == 1) {
                $res_name_str = '<a href="'.AnUrl('file').'" target="_blank">'.display_title($log_info['res_name'], $log_info['res_id']).'</a>';
            } elseif ($log_info['res_name'] == 'work') {
                $res_name_str = '<a href="'.AnUrl('work?type=2&id='.$log_info['res_id']).'" target="_blank">'._uri($log_info['res_name'], $log_info['res_id'], 'work_time').'</a>';
            } elseif ($log_info['res_name'] == 'attendance') {
                $res_name_str = '<a href="'.AnUrl('attendance').'" target="_blank">'.display_title($log_info['res_name'], $log_info['res_id']).'</a>';
            } else {
                $res_name_str = '<a href="'.AnUrl($log_info['res_name'], $log_info['res_id']).'" target="_blank">'.display_title($log_info['res_name'], $log_info['res_id']).'</a>';
            }
        }

        // 一些关联操作的日志
        //an_dump($log_info);
        if ($log_info['real_res_name']) {
            //an_dump($log_info['difference'], array('log_intro'=>$log_intro, 'notification_intro'=>$notification_intro, 'mail_intro'=>$mail_intro));
            if (empty($log_info['difference'])) {
                return $return_info;
            }
            $difference = unserialize($log_info['difference']);

            if ($log_info['real_field'] == 'assign' && $curr_user_id == 16) {
                //an_dump($difference, $log_info['difference']);
            }
            // 新建任务，并提醒
            if ($log_info['real_field'] == 'assign' && $difference) {
                if (!isset($difference['assign_id'])) {
                    return $return_info;
                }
                $action              = '分派新';
                $same_intro          = '给 '.user_helper::display_name($difference['assign_id']);
                if (isset($difference['follower_ids']) && $difference['follower_ids']) {
                    $same_intro     .= '，并提醒给：';
                    if (isset($difference['follower_ids'][0])) {
                        foreach ($difference['follower_ids'] as $v) {
                            $same_intro .= user_helper::display_name($v).' ';
                        }
                    } else {
                        $same_intro .= follower_helper::generate_follower_to_string($difference['follower_ids']);
                    }
                    $same_intro = trim($same_intro);
                }

                $log_intro          .= $action.$res_name_ch.$same_intro;
                $notification_intro .= $action.$res_name_ch.$res_name_str.$same_intro;
                $mail_intro         .= $notification_intro;

                $return_info = array('log_intro'=>$log_intro, 'notification_intro'=>$notification_intro, 'mail_intro'=>$mail_intro);
                return $return_info;
            }

            if (empty($difference) || !is_array($difference)) {
                return $return_info;
            }

            // 文件协作
            if ($log_info['real_res_name'] == 'follower' && $log_info['res_name'] == 'file') {
                    $cooperate_ids = $difference;
                    //var_dump($cooperate_ids,$cooperate_ids['id'], user_helper::display_name($cooperate_ids['id']));

                    $cooperater = '';
                    if ($cooperate_ids['res'] == 'group_id') {
                        $tmp_group_info = get_res_info('group', $cooperate_ids['id']);
                        if (!$tmp_group_info) {
                            return $return_info;
                        }

                        $cooperater = $tmp_group_info['title'];
                        if ($tmp_group_info['type'] == 1) {
                            $cooperater .= '部门';
                        } else {
                            $cooperater .= '项目';
                        }
                        $cooperater .= '的所有人';
                    } else if ($cooperate_ids['res'] == 'user_id') {
                        $cooperater = user_helper::display_name($cooperate_ids['id']);
                    } else {
                        $cooperater = '全公司';
                    }

                    if ($log_info['action'] == 'create') {
                        $log_intro          .= '协作给'.$cooperater;
                        $notification_intro .= '将'.$res_name_ch.'：'.$res_name_str.' 协作给'.$cooperater;
                    } else {
                        $log_intro          .= '删除了协作者'.$cooperater;
                        $notification_intro .= '删除了'.$res_name_ch.'：'.$res_name_str.' 的协作者'.$cooperater;
                    }
                    $mail_intro             .= $notification_intro;

                // 添加删除关注
            } elseif ($log_info['real_res_name'] == 'follower') {
                if (isset($difference[0]) && count($difference) == 1 && $difference[0] == $log_info['op_id']) {
                    if ($log_info['action'] == 'create') {
                        $log_intro          .= '关注了 '.$res_name_ch;
                        $notification_intro .= '关注了'.$res_name_ch.'：'.$res_name_str;
                    } else {
                        $log_intro          .= '取消关注 '.$res_name_ch;
                        $notification_intro .= '取消关注'.$res_name_ch.'：'.$res_name_str;
                    }
                    $mail_intro         .= $notification_intro;

                } else {
                    $tmp_users_str = '';
                    if (isset($difference[0])) {
                        foreach ($difference as $v) {
                            $tmp_users_str .= user_helper::display_name($v).' ';
                        }
                    } else {
                        $tmp_users_str .= follower_helper::generate_follower_to_string($difference);
                        //var_dump($tmp_users_str);
                    }

                    //$tmp_users_str = trim($tmp_users_str, '，');
                    if ($log_info['action'] == 'create') {
                        $log_intro          .= '提醒给 '.$tmp_users_str;
                        $notification_intro .= '将'.$res_name_ch.'：'.$res_name_str.' 提醒给'.$tmp_users_str;
                    } else {
                        $log_intro          .= '删除了关注者 '.$tmp_users_str;
                        $notification_intro .= '删除了'.$res_name_ch.'：'.$res_name_str.' 的关注者：'.$tmp_users_str;
                    }
                    $mail_intro         .= $notification_intro;

                    if (user_helper::get_user_id() == 16) {
                        //var_dump($tmp_users_str, '本丁');
                        //exit;
                    }
                }

                // 关联任务
            } elseif ($log_info['real_res_name'] == 'task_relation') {
                $action              = log_config::$action[$log_info['action']];
                $same_intro          = '子任务：'.display_title('task', $difference[0]);
                $log_intro          .= $action.$same_intro;
                if ($log_info['action'] == 'create') {
                    $notification_intro .= '为'.$res_name_ch.'：'.$res_name_str.' '.$action.$same_intro;
                } else {
                    $notification_intro .= $action.'了'.$res_name_ch.'：'.$res_name_str.' 的'.$same_intro;
                }
                $mail_intro         .= $notification_intro;

                // 为某资源上传附件
            } elseif ($log_info['real_res_name'] == 'file_relation') {
                $action              = log_config::$action[$log_info['action']];
                $same_intro          = '附件：'.display_title('file', $difference[0]);
                $log_intro          .= $action.$same_intro;
                if ($log_info['action'] == 'create') {
                    $notification_intro .= '为'.$res_name_ch.'：'.$res_name_str.' '.$action.$same_intro;
                } else {
                    $notification_intro .= $action.'了'.$res_name_ch.'：'.$res_name_str.' 的'.$same_intro;
                }
                $mail_intro         .= $notification_intro;

                // 文件回收
            } elseif ($log_info['real_res_name'] == 'garbage') {
                if ($log_info['action'] == 'create') {
                    $action = '删除了';
                } else {
                    $action = '还原了';
                }
                $log_intro          .= $action.$res_name_ch;
                $notification_intro .= $action.$res_name_ch.'：'.$res_name_str;
                $mail_intro         .= $notification_intro;
            }

            // 其它表的log处理
        } else {
            $detail_list = _model('log_detail')->getList(array('log_id'=>$log_id), ' ORDER BY `id` ASC ');
            $list = array();
            $is_new = 1;
            foreach ($detail_list as $k=>$v) {
                // 更新时间排除
                if ($v['field_name'] == 'update_time') {
                    continue;
                }

                if ($log_info['res_name'] == 'comment') {
                    $res_name = $res_info['res_name'];
                } else {
                    $res_name = $log_info['res_name'];
                }

                // 如果是日志与考勤，标题排除
                if (in_array($res_name, array('work', 'attendance')) && $v['field_name'] == 'title') {
                    continue;
                }

                $list[$v['field_name']] = $v;
                if (!empty($v['old_value'])) {
                    $is_new = 0;
                }
            }

            if ($log_info['res_name'] == 'comment') {

                $res_name_ch  = log_config::$log_res_relation[$res_info['res_name']];
                $res_name_str = '<a href="'.AnUrl($res_info['res_name'], $res_info['res_id']).'" target="_blank">'.$real_res_info['title'].'</a>';

                if ($log_info['action'] == 'create') {
                    $log_intro          .= '新增了评论';
                    $notification_intro .= '评论了'.$res_name_ch.$res_name_str;
                    $mail_intro         .= $notification_intro;
                } else if ($log_info['action'] == 'delete') {
                    $log_intro          .= '永久删除了评论';
                    $notification_intro .= '删除了'.$res_name_ch.$res_name_str.'的评论';
                    $mail_intro         .= $notification_intro;
                }  else if ($log_info['action'] == 'update') {
                    if (array_key_exists('status', $list) && count($list) == 1) {
                        if ($list['status']['old_value'] == 0 && $list['status']['old_value'] == 1) {
                            $action = '从回收站还原了';
                        } elseif ($list['status']['old_value'] == 1) {
                            $action = '删除了';
                        }
                        $log_intro          .= $action.'评论';
                        $notification_intro .= $action.$res_name_ch.'：'.$res_name_str.'的评论';
                        $mail_intro         .= $notification_intro;
                    }
                }

                // 常规的表的log处理
            } else {

                if ($is_new) {
                    $action              = log_config::$action[$log_info['action']];
                    $log_intro          .= $action.$res_name_ch;
                    $notification_intro .= $action.$res_name_ch.$res_name_str;
                    $mail_intro         .= $notification_intro;

                    // 开始与结束时间同时改
                } elseif (array_key_exists('start_time', $list) && array_key_exists('end_time', $list) && count($list) == 2) {
                    $action              = '更改';
                    $same_intro          = '开始时间为：'.time_format($list['start_time']['new_value'], 'Y-m-d').', 结束时间为：'.time_format($list['end_time']['new_value'], 'Y-m-d');
                    $log_intro          .= $action.$same_intro;
                    $notification_intro .= $action.$res_name_ch.$res_name_str.'的'.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 仅开始时间
                } elseif (array_key_exists('start_time', $list) && count($list) == 1) {
                    $action              = '更改';
                    $same_intro          = '开始时间为：'.time_format($list['start_time']['new_value'], 'Y-m-d');
                    $log_intro          .= $action.$same_intro;
                    $notification_intro .= $action.$res_name_ch.$res_name_str.'的'.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 仅结束时间
                } elseif (array_key_exists('end_time', $list) && count($list) == 1) {
                    $action              = '更改';
                    $same_intro          = '结束时间为：'.time_format($list['end_time']['new_value'], 'Y-m-d');
                    $log_intro          .= $action.$same_intro;
                    $notification_intro .= $action.$res_name_ch.$res_name_str.'的'.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 任务项目
                } elseif (array_key_exists('group_id', $list) && $log_info['res_name'] == 'task') {
                    //eg:解决了任务
                    $same_intro          = '转移到项目：'.display_title('group', $list['group_id']['new_value']);
                    $log_intro          .= '将任务'.$same_intro;
                    $notification_intro .= '将任务:'.$res_name_str.' '.$same_intro;;
                    $mail_intro         .= $notification_intro;

                // 转派
                } elseif (array_key_exists('assign_id', $list)) {
                    $same_intro          = '转派给：'.user_helper::display_name($list['assign_id']['new_value']);
                    $log_intro          .= $same_intro;
                    $notification_intro .= '将'.$res_name_ch.':'.$res_name_str.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 任务状态
                } elseif (array_key_exists('task_status', $list)) {
                    //eg:解决了任务
                    $same_intro          = task_config::$task_status_action[$list['task_status']['new_value']].'了'.$res_name_ch;
                    $log_intro          .= $same_intro;
                    $notification_intro .= $same_intro.'：'.$res_name_str;
                    $mail_intro         .= $notification_intro;

                    // 标题
                } elseif (array_key_exists('title', $list)) {
                    $action              = '更改';
                    if (in_array($log_info['res_name'], array('file', 'dir'))) {
                        $same_intro          = '名字为：'.$list['title']['new_value'];
                    } else {
                        $same_intro          = '标题为：'.$list['title']['new_value'];
                    }
                    $res_name_str = '<a href="'.AnUrl($log_info['res_name'], $log_info['res_id']).'" target="_blank">'.$list['title']['old_value'].'</a>';
                    if ($log_info['res_name'] == 'dir') {
                        $res_name_str = '<a href="'.AnUrl('file/dir').'" target="_blank">'.$list['title']['old_value'].'</a>';
                    }
                    $log_intro          .= $action.$same_intro;
                    $notification_intro .= $action.$res_name_ch.$res_name_str.'的'.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 内容
                } elseif (array_key_exists('content', $list) && count($list) == 1) {
                    $action              = '更改';
                    $same_intro          = '内容为：'.AnString::stripHtml($list['content']['new_value'], '20');
                    $log_intro          .= $action.$same_intro;
                    $notification_intro .= $action.$res_name_ch.$res_name_str.'的'.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 分类
                } elseif (array_key_exists('category_id', $list) && count($list) == 1) {
                    $action              = '更改';
                    $same_intro          = '分类为：'.display_title('category', $list['category_id']['new_value']);
                    $log_intro          .= $action.$same_intro;
                    $notification_intro .= $action.$res_name_ch.$res_name_str.'的'.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 回收与还原
                } elseif (array_key_exists('status', $list) && $list['status']['old_value']) {
                    if ($list['status']['old_value'] == 0 && $list['status']['old_value'] == 1) {
                        $action = '从回收站还原了';
                    } elseif ($list['status']['old_value'] == 1) {
                        $action = '删除了';
                    }
                    $log_intro          .= $action.$res_name_ch;
                    $notification_intro .= $action.$res_name_ch.'：'.$res_name_str;
                    $mail_intro         .= $notification_intro;

                    // 文件上传新版本
                } elseif (array_key_exists('version_id', $list) && $log_info['res_name'] == 'file') {
                    $same_intro = '上传新文件，生成了版本 '.file_helper::get_version_order($list['version_id']['new_value']);
                    $log_intro          .= $same_intro;
                    $notification_intro .= '为'.$res_name_ch.'：'.$res_name_str.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 日志批阅
                } elseif (array_key_exists('work_status', $list) && $log_info['res_name'] == 'work') {
                    $action = '批阅了';
                    $log_intro          .= $action.$res_name_ch;
                    $notification_intro .= $action.$res_name_ch.'：'.$res_name_str;
                    $mail_intro         .= $notification_intro;

                } elseif (array_key_exists('work_time', $list) && $log_info['res_name'] == 'work') {
                    $action              = '更改';
                    $same_intro          = '时间为：'.$list['work_time']['new_value'];
                    $res_name_str = '<a href="'.AnUrl('work').'" target="_blank">'.$list['work_time']['old_value'].'</a>';

                    $log_intro          .= $action.$res_name_ch.$same_intro;
                    $notification_intro .= $action.$res_name_ch.$res_name_str.$same_intro;
                    $mail_intro         .= $notification_intro;

                    // 考勤批准与打回
                } elseif (array_key_exists('attendance_status', $list) && $log_info['res_name'] == 'attendance') {
                    $action              = attendance_config::$attendance_status[$list['attendance_status']['new_value']];
                    $log_intro          .= $action.$res_name_ch;
                    $notification_intro .= $action.$res_name_ch.'：'.$res_name_str;
                    $mail_intro         .= $notification_intro;

                } else {
                    $action              = log_config::$action[$log_info['action']];
                    $log_intro          .= $action.$res_name_ch;
                    $notification_intro .= $action.$res_name_ch.$res_name_str;
                    $mail_intro         .= $notification_intro;
                }
            }
        }

        $return_info = array('log_intro'=>$log_intro, 'notification_intro'=>$notification_intro, 'mail_intro'=>$mail_intro);
        if (isset($list) && $list) {
            $return_info['detail_list'] = $list;
        } else {
            $return_info['detail_list'] = array();
        }
        return $return_info;
    }

    /**
     * 取得日志信息
     * @param int $id
     * @return array
     */
    public static function get_log_info($id)
    {
        if (empty($id)) {
            return array();
        }

        return _uri('log', (int)$id);
    }

    /**
     * 取得最近log (暂时在任务列表展示中用到)
     * @param string $res_name
     * @param int $res_id
     * @param datetime $add_time
     * @param string $field_name
     * @return array
     */
    public static function get_last_access_log($res_name, $res_id, $add_time = '', $field_name = '')
    {
        $filter = array('res_name'=>$res_name, 'res_id'=>$res_id);
        if ($field_name) {
            $filter['real_field'] = $field_name;
        }
        if ($add_time) {
            $filter['add_time >'] = $add_time;
        }

        $log_info = _model('log')->read($filter, 'ORDER BY `id` DESC');
        if (!$log_info) {
            return array();
        }

        $log_detail_list = _model('log_detail')->getList(array('log_id'=>$log_info['id']));
        $return_info = array();
        foreach ($log_detail_list as $v) {
            if ($v['field_name'] == $field_name && $v['old_value']) {
                $return_info = $v;
            }
        }

        return $return_info;
    }


    /**
     * @param string $word 日志内容
     * @TODO 文件没有可写权限未使用
     */
    public static function add_pay_log($word = '', $type = '1')
    {
        $time = date('Y-m-d', time());
        $type = $type == 1 ? 'success' : 'error';
        $file = SITE_URL.'/log/'.$time.'-'.$type.'-log.log';
        if (!is_file($file)) {
            $fp=fopen($file, "w+");
            if ( !is_writable($file) ){
                //chmod("$file", 0755);
                die("文件:" .$file. "不可写，请检查！");
            }
            //chmod("$file", 0755);
            fclose($fp);
        }
        $data = file_get_contents($file) || '';
        $data .= "执行日期：".date("Y-m-d H:i:s",time())."\n".'&nbsp;&nbsp;&nbsp;&nbsp;'.$word."\n";
        file_put_contents($file, $data);
        //var_dump($data);
    }

    public static function create_lenovo_pay_log($param = array())
    {
        $check_param = array(
            'transaction_id' => '',
            'order_id'       => '',
            'pay_type'       => '',
            'lenovo_id'         => '',
            'price'    => '',
            'pay_status'   => '',
            'pay_time'   => '',
            'attach'     =>'',
            'data'        => ''
        );

        $info = array_intersect_key(array_merge($check_param, $param), $check_param);
        _model('lenovowap_pay_log')->create($info);
    }

    /**
     * @param $word
     * @param string $type
     * @param string $res_name
     * @param string $res_id
     * @return bool
     */
    public static function create_pay_log($pay_type = 'alipay', $param = array())
    {
        $check_param = array(
            'transaction_id' => '',
            'order_id'       => '',
            'pay_type'       => '',
            'openid'         => '',
            'total_price'    => '',
            'trade_status'   => '',
            'remarks'        => ''
        );
        switch ($pay_type) {
            case 'alipay':
            case 1:
                $pay_type = 1;
                break;
            case 'quickpay':
            case 2:
                $pay_type = 2;
                break;
            case 'tenpay':
            case 3:
                $pay_type = 3;
                break;
            default :
                $pay_type = 4;
                break;
        }

        $info = $param;
        $info['pay_type'] = $pay_type;
        $info = array_intersect_key(array_merge($check_param, $info), $check_param);
        _model('pay_log')->create($info);
    }

    /**
     * @param $word
     * @param string $type
     * @param string $res_name
     * @param string $res_id
     * @return bool
     */
    public static function create_refund_log($pay_type = 'alipay', $param = array())
    {
        $check_param = array(
            'transaction_id' => '',
            'order_id'       => '',
            'refund_id'      => '',
            'transaction_refund_id' => '',
            'refund_channel' => '',
            'refund_fee'     => '',
            'refund_status'  => '',
            'ret_msg'         => ''
        );
        switch ($pay_type) {
            case 'alipay':
            case 1:
                $pay_type = 1;
                break;
            case 'quickpay':
            case 2:
                $pay_type = 2;
                break;
            case 'tenpay':
            case 3:
                $pay_type = 3;
                break;
            default :
                $pay_type = 4;
                break;
        }

        $info = $param;
        $info['refund_channel'] = $pay_type;
        $info = array_intersect_key(array_merge($check_param, $info), $check_param);
        _model('refund_log')->create($info);
    }
}
?>